package com.sendi.sql;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;

import com.sendi.system.util.common.MutiFieldSorter;
import com.sendi.system.util.common.ReflectUtil;
import com.sendi.system.util.common.SortInformation;
import com.sendi.system.util.common.StringUtil;
 

public class GroupByUtil {
 	/*
	 * 统计动作
	 */
	public final static int SumAction=1;
	public final static int MaxAction=2;
	public final static int MinAction=3;
	public final static int AvgAction=4;
	public final static int CountAction=5;
	
	Collator   c = Collator.getInstance(Locale.CHINA);
	Class cs=null;  //注意的数据源所对应的类对像的Class
	/*
	 * 统计分组信息,就是标签中的isgroupby="YES"的字段
	 */
	private SortInformation MutiFieldSorter[]=null;
	
	/*
	 * 排序信息，以后扩展用于点击标题时排序
	 */
	private String detailsortfildrecord="";
	/*
	 * 分组定界
	 */
	private ArrayList<Integer> groupbyIndex=new ArrayList<Integer>();
	
	private ArrayList<DataSource> source=null;
	
	/*
	 * 分组统计后的结果
	 */
	public ArrayList<DataSource> groupReult=new ArrayList<DataSource>();
	
	 
	/*
	 * 统计动作的数据列
	 */
	private ArrayList<FieldInf> reportActionfileds=new ArrayList<FieldInf>();
	
	int reportActionfiledslen;
	private HashMap<String, Field> field;  //反射时用到
	/*
	 * 是否执行了数据源排序与归类
	 */
	private boolean isGroupByDataSource=false;
 
	private String  finalinvokemethod="";
	
	private LinkedHashMap<String, FieldInf> allfieldinf;
	
	private HashMap<String, Field> allField=null;//所有字段的java.lang.reflect.Field的集合引用
	private HashMap<String,Method>  methodReflect=null;//需要反射调用的Method集合
	private String modulename="";
	/*
	 * 二级统计，比如，开始是stpname,exchangename,eln,slc 是按这分组的，现有一种需要就是求出的一个指标值，需要再进行一次求和
	 * ，是按stpname,exchangename,eln来分组的，最后就可以求分担比例.该功能就是针对这样一种需要开发的。
	 * secondGroupy 语法如下：stpname,exchangename,eln#msu,oct#totalmsu,totaloct#methodname
	 * 意思是当前面的数据分组统计完成后，再对 stpname,exchangename,eln分组，然后分别求msu，oct的各值，最后再求到的和值赋给totalmsu,totaloct
	 *  stpname,exchangename,eln  须是第一次分组的中的字段,methodname为当把totalmsu,totaloct求出来后，需要反射调用的方法
	 *  其实最好的办法是把stpname,exchangename,eln选连起来，做为一个字段，这样的可以减少反射带来的的性能损失
	 *  注意msu，oct 与totalmsu,totaloct在位置 上必须对应
	 */
	private String secondGroupy;
	/*
	 * fixed
	 * automatic 默认。列宽度由单元格内容设定
	 */
	private String detailtablelayout="automatic";
	
	private HashMap<String,SecondGroupByHashMap> secondGroupyresult;
	 
	/*
	 * 需要排名的字段
	 */
	private String rankfield;
	
	
	public GroupByUtil()
	{
		
	}
	
	private void MakeSecondGroupyresult()
	{
		 long start=System.currentTimeMillis();
		String groupby[]=secondGroupy.split("#")[0].split(",");
		String sumfield[]=secondGroupy.split("#")[1].split(",");
		String acceptfeild[]=secondGroupy.split("#")[2].split(",");
		String methodname=secondGroupy.split("#").length==4?secondGroupy.split("#")[3]:"";
		if(methodname!=null&&methodname.trim().length()>0)
		{
			if(methodReflect==null)
				methodReflect=new HashMap<String, Method>();
			try {
				Method me=cs.getDeclaredMethod(methodname);
				me.setAccessible(true);
				methodReflect.put(methodname, me);
			} catch (SecurityException e1) {
			 
				e1.printStackTrace();
			} catch (NoSuchMethodException e1) {
			 
				e1.printStackTrace();
			}
		}
		secondGroupyresult=new HashMap<String, SecondGroupByHashMap>();
		for(String fe:sumfield)  //生成数据存储空间
		{
			FieldInf fei=allfieldinf.get(fe);
			SecondGroupByHashMap sgb=new SecondGroupByHashMap(fei.getFieldType());
			secondGroupyresult.put(fe, sgb);
		}
		
		for(Object d:groupReult)
		{
			for(String fe:sumfield)  
			{
				Object o=ReflectUtil.getReflectFieldValue(d, allField.get(fe));
				StringBuffer key=new StringBuffer("");
				for(String k :groupby)
				{
					key.append((String)ReflectUtil.getReflectFieldValue(d, allField.get(k)));
				}
			 	SecondGroupByHashMap sgb=secondGroupyresult.get(fe);
				sgb.MakeSumGroupAction(key.toString(), o);
			}
	 	}
		int lensum=sumfield.length;
		for(Object e:groupReult)
		{
			StringBuffer key=new StringBuffer("");
			for(String k :groupby)
			{
				key.append((String)ReflectUtil.getReflectFieldValue(e, allField.get(k)));
			}
			for(int ks =0;ks<lensum;ks++)
			{
				SecondGroupByHashMap sgb=secondGroupyresult.get(sumfield[ks]);
				sgb.SetSecondGroupByresult(e, key.toString(), allField.get(acceptfeild[ks]));
		 	}
			if(methodname!=null&methodname.trim().length()>0)
			{
				ReflectUtil.InvokeMethdToRun(e, methodReflect.get(methodname));
			}
	  		
		}
		System.out.println("二次统计所用时间为："+(System.currentTimeMillis()-start)/1000.0);
 	}
 


	/*
	 * 判断统计动作的值
	 */
	public static int JudgeGroupActionType(String groupactionname)
	{
		//-1说明没有任务统计动作
		if(groupactionname.equalsIgnoreCase("SumAction"))
		{
			return GroupByUtil.SumAction;
		}
		else if(groupactionname.equalsIgnoreCase("MaxAction"))
		{
			return GroupByUtil.MaxAction;
		}
		else if(groupactionname.equalsIgnoreCase("MinAction"))
		{
			return GroupByUtil.MinAction;
		}
		else if(groupactionname.equalsIgnoreCase("AvgAction"))
		{
			return GroupByUtil.AvgAction;
		}
		else if(groupactionname.equalsIgnoreCase("CountAction"))
		{
			return GroupByUtil.CountAction;
		}
		else return -1;
	}
	
 
 

	/*
	 * 统计操作，生成统计操作后结果集
	 */
	public void MakeGroupReult()
	{
		System.out.println("统计数据源大小为："+this.source.size());
		if(!isGroupByDataSource)
		{
			GroupByDataSource();
		}
		
		long starttime=System.currentTimeMillis();
		/*
		 * 是否具有求最大值的动作
		 */
		boolean ishaveMaxAction=false;
		/*
		 * 如果具有求最大值的动作，他在groupActionfileds中的index
		 */
		int MaxActionIndexingroupActionfileds=0;
		/*
		 * 是否具有求最小值的动作
		 */
		boolean ishaveMinAction=false;
		
		/*
		 * 如果具有求最小值的动作，他在groupActionfileds中的index
		 */
		int MinActionIndexingroupActionfileds=0;
		int index=0;
		for(FieldInf field:reportActionfileds)
		{
			if(field.getGroupByAction()==MaxAction&&!ishaveMaxAction)
			{
				ishaveMaxAction=true;
				MaxActionIndexingroupActionfileds=index;
			}
			else if(field.getGroupByAction()==MinAction&&!ishaveMinAction)
			{
				ishaveMinAction=true;
				MinActionIndexingroupActionfileds=index;
			}
			//如果已找到最大求值的，直接退出
			if(ishaveMaxAction)
				break;
		 
			index++;
			
		}
		if(ishaveMaxAction) //如果有最大值的动作，则去掉最小值的动作
		{
			ishaveMinAction=false;
		}
	 
		 	//循环每一个分组的数据，取得统计结果
			int startindex=0;
			int endindex=0;
			int exceptionindex=0;
			for (Integer in:groupbyIndex)
			{
				Object groupbyResult=null;
				endindex=in;
			 	if(ishaveMaxAction)
				{
					FieldInf fieldInf=reportActionfileds.get(MaxActionIndexingroupActionfileds);
					groupbyResult=GroupByAction(startindex, endindex, fieldInf);
					exceptionindex= MaxActionIndexingroupActionfileds;
				}
				else if(ishaveMinAction)
				{
					FieldInf fieldInf=reportActionfileds.get(MinActionIndexingroupActionfileds);
					groupbyResult=GroupByAction(startindex, endindex, fieldInf);
					exceptionindex=MinActionIndexingroupActionfileds;
				}
				else
				{
					FieldInf fieldInf=reportActionfileds.get(0); //如果没有最大，最小的动作，就用第一个
					groupbyResult=GroupByAction(startindex, endindex, fieldInf);
					exceptionindex=0;
		 		}
				 
			  	 	for(int j=0;j<reportActionfiledslen;j++)
					{
			  	 		//System.out.println("exceptionindex"+exceptionindex+"--j--"+j);
			  	 		if(j!=exceptionindex)
			  	 		{
			  	 			FieldInf fieldInf=reportActionfileds.get(j);
				  	 		//System.out.println("########"+fieldInf.getFieldcomment()+"\t"+fieldInf.getGroupByAction());
				  	 		Object o=GroupByAction(startindex, endindex, fieldInf);
				  	 	 	ReflectUtil.copyFiledValueFromOtherobj(o, groupbyResult, fieldInf.getGroupByActionPointFiledobj());	
				  	 		//System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<");
			  	 		}
			  	 		
					}
			  	 	if(this.finalinvokemethod!=null&&finalinvokemethod.trim().length()>0)
			  	 	{
			  	 		ReflectUtil.InvokeMethdToRun(groupbyResult, finalinvokemethod);
			  	 	 
			  	 	}
			  	 	DataSource ds=(DataSource)groupbyResult;
			   	 	groupReult.add(ds);
			  	 	startindex=(in+1); //下一个开始的位置
		 	}
			
			if(this.secondGroupy!=null&&secondGroupy.trim().length()>0)
			{
				MakeSecondGroupyresult();
			}
			if(this.rankfield!=null&&this.rankfield.trim().length()>0)
			{
				 Ranking();
			}
			
			
			//System.out.println("统计所用时间为：..."+(System.currentTimeMillis()-starttime)/1000);
	 	}
 	
	
	/*
	 * 排名操作
	 */
	private void Ranking()
	{
		if(this.groupReult.size()>0)
		{
			 	SortInformation RankingField[]=new SortInformation[1];
			 	SortInformation sf=new SortInformation();
			 	FieldInf f=	allfieldinf.get(this.rankfield);
				sf.fieldname=f.getFieldname();
				sf.fieldtype=StringUtil.getSortFieldType(f.getFieldType());
			 	sf.sorttype="desc";
				
				RankingField[0]=sf;
				MutiFieldSorter mfs=new MutiFieldSorter(RankingField,cs);
				Collections.sort(groupReult, mfs);//对结果数据源进行按排名字段排序
				int i=1;
				for(DataSource ds:groupReult)
				{
					ds.setPerformanceRank(i);
					i++;
				}
	 	}
	}
	/*
	 * 统计操作
	 */
	private Object GroupByAction(int startindex,int endindex,FieldInf fieldInf)
	{
		Object groupbyResult=null; //统计后取值的对像
		Object groupbyActionResult=null;//统计结果表示
		int Objectindex=0;
		switch (fieldInf.getGroupByAction()) {
		case GroupByUtil.SumAction:
			groupbyActionResult=Sum(startindex, endindex, fieldInf);
			Objectindex=startindex;
	 		break;
		case GroupByUtil.AvgAction:
			groupbyActionResult=Avg(startindex, endindex, fieldInf);
			Objectindex=startindex;
			break;
		case GroupByUtil.CountAction:	
			groupbyActionResult=Count(startindex, endindex,fieldInf);
			Objectindex=startindex;
		 	break;
		case GroupByUtil.MaxAction:
			MaxResult maxresult=Max(startindex, endindex, fieldInf);
			Objectindex=maxresult.maxindex;
			groupbyActionResult=maxresult.getMaxResult();
	 	break;
		case GroupByUtil.MinAction:
	 		MinResult minresult=Min(startindex, endindex, fieldInf);
			Objectindex=minresult.minindex;
			groupbyActionResult=minresult.getMinResult();
	 	break;
	 	default:
			break;
		}
 		try {
			groupbyResult=this.source.get(Objectindex).clone(); 
	 	} catch (CloneNotSupportedException e) {
	 		e.printStackTrace();
		}  
 		 
		ReflectUtil.setFieldValueByReflect(groupbyResult, fieldInf.getGroupByActionAcceptField(), fieldInf.getFieldType(),groupbyActionResult);
		if(fieldInf.getGroupByActionPointMethod()!=null)
		{
			for(String ff:fieldInf.getGroupByActionPointMethod())
			{
				ReflectUtil.InvokeMethdToRun(groupbyResult, ff);
			}
		}
		
		DataSource ds=(DataSource)groupbyResult;
  	 	ds.setEndindex(endindex);
  	 	ds.setStartindex(startindex);
   		return groupbyResult;
	}
	
  	
	/*
	 * 注入数据源,分组统计动作字段
	 * reportActionfileds 统计动作的列
	 * groupbyfieldss 分组的字段
	 * allfieldinf 所有列的信息
	 * 
	 */
	public GroupByUtil( ArrayList<DataSource> source, ArrayList<FieldInf> reportActionfileds, ArrayList<FieldInf> groupbyfieldss,LinkedHashMap<String, FieldInf> allfieldinf) {
		//System.out.println("数据源大小："+source.size());
		this.allfieldinf=allfieldinf;
		getGroupbyfields(groupbyfieldss);
		this.source = source;
	 	this.reportActionfileds = reportActionfileds;
	 	reportActionfiledslen=reportActionfileds.size();
	 	}
	

	private void getGroupbyfields(ArrayList<FieldInf> groupActionfileds)
	{
		int size=groupActionfileds.size();
	 
		MutiFieldSorter=new SortInformation[size];
		int i=0;
		for(FieldInf f:groupActionfileds)
		{
			SortInformation sf=new SortInformation();
			sf.fieldname=f.getFieldname();
			sf.fieldtype=StringUtil.getSortFieldType(f.getFieldType());
			sf.sorttype=f.getGroupbyType();
	 		MutiFieldSorter[i]=sf;
			i++;
		}
		 
	}
 	
	/*
	 * 根据排序字段，对数据库进行分组排序，并拿到分组的定界
	 */
	 
	public void GroupByDataSource()
	{
		long start=System.currentTimeMillis();
		if(MutiFieldSorter==null||MutiFieldSorter.length==0)
		{
			try {
				throw new Exception("分组信息不能为空...............");
			} catch (Exception e) {
				 
				e.printStackTrace();
				return ; 
			}
		}
		if(source==null||source.size()==0)
		{
			try {
				throw new Exception("数据源不能为空...............");
			} catch (Exception e) {
		 		e.printStackTrace();
				return ; 
			}
		}
		
		field=new HashMap<String, Field>();
		cs=source.get(0).getClass();
	  	for(SortInformation k:MutiFieldSorter)
	  	{
	  		String fname=k.fieldname;
	  		Field f=null;
			try {
				f=cs.getDeclaredField(fname);
				f.setAccessible(true);
				field.put(fname, f);
			}catch (Exception e) {
				 e.printStackTrace();
			}
	  	}
	  	
	  	//把所有字段对应Field放入集合中
		allField=new HashMap<String, Field>();
	 	Iterator<String> it=allfieldinf.keySet().iterator();
	 	while(it.hasNext())
	 	{
	 		String key=it.next();
	 		Field f=null;
			try {
				try
				{
					f=cs.getDeclaredField(key);
				}
				catch (Exception e) {
					 f=cs.getSuperclass().getDeclaredField(key);
				}
				
				f.setAccessible(true);
				allField.put(key, f);
			}catch (Exception e) {
		 		 System.out.println("GroupByDataSource()把所有字段的Field放入集合中出错："+e.getMessage());
			}
	 	}
	 	
	 	
	  	
		MutiFieldSorter omf=new MutiFieldSorter(MutiFieldSorter,cs);
	 	Collections.sort(source, omf);//List 数据源进行排序
	 	
	 	/*for(DataSource ds:source)
	 	{
	 		LinkDataSource lds=(LinkDataSource)ds;
	 		System.out.println(lds.getExchangename()+"\t"+lds.getDpcname()+"\t"+lds.getLinkname()+"\t"+lds.getStarttime()+"\t"+lds.getEndtime()+"\t"+lds.getSendoct());
	 	}*/
	 	int size=source.size();
	 	for(int i=0;i<size;i++)
	 	{
	 		Object o1,o2;
	 		if(i!=size-1)
	 		{
	 			o1=source.get(i);
		 		o2=source.get(i+1);
		 		if(!CompareReflectFieldValue(o1, o2))
		 		{
		 			groupbyIndex.add(Integer.valueOf(i));
		 		}
	 		}
	 		else
	 		{
	 	  	 groupbyIndex.add(Integer.valueOf(i));	
		 	}
	 		
	 		
	 	
	 	}
	  
	 	isGroupByDataSource=true;
	 	System.out.println("排序所用时间为：..."+(System.currentTimeMillis()-start)/1000);
 	}
	  
	/*
	 * index 是数据源分界的结束位置，fieldname为字段名，fieldtype为字段类型
	 * 目前支持INT,LONG,DOUBLE,FLOAT,DATE
	 */
	private MaxResult Max(int startindex,int endindex,FieldInf fieldInf)
	{
		String fieldname=fieldInf.getFieldname(), fieldtype=fieldInf.getFieldType();
		MaxResult maxResult=new MaxResult();
		maxResult.maxindex=startindex;
		maxResult.type=fieldtype;
		for(int i=startindex;i<=endindex;i++)
		{
			
			Object o1=ReflectUtil.getReflectFieldValue(source.get(i),fieldname);
			if(i==startindex)
			{
				if(fieldtype.equalsIgnoreCase("INT"))
				{
					maxResult.maxint=Integer.parseInt(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("LONG"))
				{
					maxResult.maxlong=Long.parseLong(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("FLOAT"))
				{
					maxResult.maxfloat=Float.parseFloat(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("DOUBLE"))
				{
					maxResult.maxdouble=Double.parseDouble(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("DATE"))
				{
					maxResult.maxdate=pareDate(o1);
				}
				 
			}
			else
			{
				if(fieldtype.equalsIgnoreCase("INT"))
				{
					int temp=Integer.parseInt(o1.toString());
					if(temp-maxResult.maxint>0)
					{
						maxResult.maxint=temp;
						maxResult.maxindex=i;
					}
					
				}
				else if(fieldtype.equalsIgnoreCase("LONG"))
				{
					long temp=Long.parseLong(o1.toString());
					if(temp-maxResult.maxlong>0)
					{
						maxResult.maxlong=temp;
						maxResult.maxindex=i;
					}

				}
				else if(fieldtype.equalsIgnoreCase("FLOAT"))
				{
					float temp=Float.parseFloat(o1.toString());
				  	if(temp-maxResult.maxfloat>0)
					{
				  		maxResult.maxfloat=temp;
				  		maxResult.maxindex=i;
					}
				}
				else if(fieldtype.equalsIgnoreCase("DOUBLE"))
				{
					double temp=Double.parseDouble(o1.toString());
					if(temp-maxResult.maxdouble>0)
					{
						maxResult.maxdouble=temp;
						maxResult.maxindex=i;
					}
				}
				else if(fieldtype.equalsIgnoreCase("DATE"))
				{
					Date temp=pareDate(o1);
					
					if(temp.getTime()-maxResult.maxdate.getTime()>0)
					{
						maxResult.maxdate=temp;
						maxResult.maxindex=i;
					}
				}
				
			}
 		}
		return maxResult;
		
	}
	
	/*
	 * CountAction
	 */
	private int Count(int startindex,int endindex,FieldInf fieldInf)
	{
		String countdetail=fieldInf.getCountdetail();
		if(countdetail==null||countdetail.trim().length()==0)
		{
			return endindex-startindex+1;
		}
		else
		{
			String[] infor=countdetail.split(",");
			int len=infor.length;
			HashSet<String> resust=new HashSet<String>();
			StringBuffer sb=new StringBuffer("");
			if(len>=2&&infor[0].equalsIgnoreCase("distinct"))
			{
				
				for(int j=startindex;j<=endindex;j++)
				{
					for(int i=1;i<len;i++)
					{
						Object o1=ReflectUtil.getReflectFieldValue(source.get(j),infor[i]);
						sb.append((String)o1);
					}
					resust.add(sb.toString());
					sb=new StringBuffer("");
		 		}
				
			}
			
			return resust.size();
		}
		
	}
	
	/*
	 * 日期转换类，默认日期字符串格式为yyyyMMddhhmmss
	 */
	private Date pareDate(Object obj , String... forstr )
	{
		SimpleDateFormat sdf=null;
		/*if(forstr==null&&forstr.length==0)
		{
			sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		}
		else
		{
			sdf = new SimpleDateFormat(forstr[0]);
		}*/
		sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		if(obj==null)
			try {
				return sdf.parse("10000101010101"); //给最少的日期值
			} catch (ParseException e) {
		 		e.printStackTrace();
			}
		if(obj.getClass().getName().equalsIgnoreCase("java.util.Date"))
		{
			return (Date)obj;
		}
		else if(obj.getClass().getName().equalsIgnoreCase("java.lang.String"))
		{
			try {
				return sdf.parse(obj.toString());
			} catch (ParseException e) {
		 		e.printStackTrace();
			}
		}
		return null;
	}
	
	private MinResult Min(int startindex,int endindex,FieldInf fieldInf)
	{
		String fieldname=fieldInf.getFieldname(), fieldtype=fieldInf.getFieldType();
		MinResult minResult=new MinResult();
		minResult.minindex=startindex;
		minResult.type=fieldtype;
		for(int i=startindex;i<=endindex;i++)
		{
			Object o1=ReflectUtil.getReflectFieldValue(source.get(i),fieldname);
			if(i==startindex)
			{
				if(fieldtype.equalsIgnoreCase("INT"))
				{
					minResult.minint=Integer.parseInt(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("LONG"))
				{
					minResult.minlong=Long.parseLong(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("FLOAT"))
				{
					minResult.minfloat=Float.parseFloat(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("DOUBLE"))
				{
					minResult.mindouble=Double.parseDouble(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("DATE"))
				{
					minResult.mindate=pareDate(o1);
				}
				 
			}
			else
			{
				if(fieldtype.equalsIgnoreCase("INT"))
				{
					int temp=Integer.parseInt(o1.toString());
					if(temp-minResult.minint<0)
					{
						minResult.minint=temp;
						minResult.minindex=i;
					}
					
				}
				else if(fieldtype.equalsIgnoreCase("LONG"))
				{
					long temp=Long.parseLong(o1.toString());
					if(temp-minResult.minlong<0)
					{
						minResult.minlong=temp;
						minResult.minindex=i;
					}

				}
				else if(fieldtype.equalsIgnoreCase("FLOAT"))
				{
					float temp=Float.parseFloat(o1.toString());
				  	if(temp-minResult.minfloat<0)
					{
				  		minResult.minfloat=temp;
				  		minResult.minindex=i;
					}
				}
				else if(fieldtype.equalsIgnoreCase("DOUBLE"))
				{
					double temp=Double.parseDouble(o1.toString());
					if(temp-minResult.mindouble<0)
					{
						minResult.mindouble=temp;
						minResult.minindex=i;
					}
				}
				else if(fieldtype.equalsIgnoreCase("DATE"))
				{
					Date temp=pareDate(o1);
					
					if(temp.getTime()-minResult.mindate.getTime()<0)
					{
						minResult.mindate=temp;
						minResult.minindex=i;
					}
				}
	 		}
	 		}
		
		return minResult;
	}
	/*
	 * 无日期类型的平均值
	 */
	private Object Avg(int startindex,int endindex,FieldInf fieldInf)
	{
		String fieldname=fieldInf.getFieldname(), fieldtype=fieldInf.getFieldType();
		Object o1=Sum(startindex, endindex, fieldInf);
		int sumint=0;
		long sumlong=0l;
		float sumfloat=0.0f;
	  	double sumdouble=0.0d;
	  	if(o1!=null)
	  	{
	  		int total=endindex-startindex+1;
	  		if(fieldtype.equalsIgnoreCase("INT"))
			{
				sumint=Integer.parseInt(o1.toString());
				return sumint/total;
			}
			else if(fieldtype.equalsIgnoreCase("LONG"))
			{
				sumlong=Long.parseLong(o1.toString());
				return sumlong/total;
			}
			else if(fieldtype.equalsIgnoreCase("FLOAT"))
			{
				sumfloat=Float.parseFloat(o1.toString());
				return sumfloat/total;
			}
			else if(fieldtype.equalsIgnoreCase("DOUBLE"))
			{
				sumdouble=Double.parseDouble(o1.toString());
				return sumdouble/total;
			}
			else
			{
				return null;
			}
	  		
	  		
	  	}
	  	return null;
 	}
	/*
	 * 无日期类型的求和值
	 */
	private Object Sum(int startindex,int endindex,FieldInf fieldInf)
	{
		String fieldname=fieldInf.getFieldname(), fieldtype=fieldInf.getFieldType();
		int sumint=0;
		long sumlong=0l;
		float sumfloat=0.0f;
	  	double sumdouble=0.0d;
		 
		for(int i=startindex;i<=endindex;i++)
		{
			
			Object o1=ReflectUtil.getReflectFieldValue(source.get(i),fieldname);
			if(i==startindex)
			{
				if(fieldtype.equalsIgnoreCase("INT"))
				{
					sumint=Integer.parseInt(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("LONG"))
				{
					sumlong=Long.parseLong(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("FLOAT"))
				{
					sumfloat=Float.parseFloat(o1.toString());
				}
				else if(fieldtype.equalsIgnoreCase("DOUBLE"))
				{
					sumdouble=Double.parseDouble(o1.toString());
				}
			 
				 
			}
			else
			{
				if(fieldtype.equalsIgnoreCase("INT"))
				{
					int temp=Integer.parseInt(o1.toString());
					sumint+=temp;
			 	}
				else if(fieldtype.equalsIgnoreCase("LONG"))
				{
					long temp=Long.parseLong(o1.toString());
				 	sumlong+=temp;
				 
				}
				else if(fieldtype.equalsIgnoreCase("FLOAT"))
				{
					float temp=Float.parseFloat(o1.toString());
					sumfloat+=temp;
			 	}
				else if(fieldtype.equalsIgnoreCase("DOUBLE"))
				{
					double temp=Double.parseDouble(o1.toString());
					sumdouble+=temp;
		 		}
	 		}
	 		}
		
		
		if(fieldtype.equalsIgnoreCase("INT"))
		{
			return sumint;
		}
		else if(fieldtype.equalsIgnoreCase("LONG"))
		{
			return sumlong;
		}
		else if(fieldtype.equalsIgnoreCase("FLOAT"))
		{
			return sumfloat;
		}
		else if(fieldtype.equalsIgnoreCase("DOUBLE"))
		{
			return sumdouble;
		}
		else
			return null;
 		
	}

	 
	
	/*
	 *  利用反射比较两个字段是否相等
	 */
	private boolean CompareReflectFieldValue(Object o1,Object o2)
	{
		int result=0;
		for( SortInformation sf: MutiFieldSorter)
		{
	 		Field f=null;
			try {
				f=field.get(sf.fieldname);
			 	Object of1=f.get(o1);
				Object of2=f.get(o2);
				if(sf.fieldtype.equalsIgnoreCase("DATE"))
				{
					Date d1=(Date)of1;
					Date d2=(Date)of2;
					if(d1.getTime()-d2.getTime()>0)
					{
						result=1;
					}
					else if(d1.getTime()-d2.getTime()<0)
					{
						result=-1;
					}
					
					
				}
				else if(sf.fieldtype.equalsIgnoreCase("Number"))
				{
					
					Number n1=(Number)of1;
					Number n2=(Number)of2;
					if(n1.doubleValue()-n2.doubleValue()>0)
					{
						result=1;
					}
					else if(n1.doubleValue()-n2.doubleValue()<0)
					{
						result=-1;
					}
					
				}
				else
				{
					
			 		result=c.compare(String.valueOf(of1), String.valueOf(of2));
			 	}
				
				if(result==0)
				{
					continue;
				}
				else
				{
					break;
				}
	 			
			} catch (SecurityException e) {
		 		e.printStackTrace();
			}  catch (IllegalArgumentException e) {
		 		e.printStackTrace();
			} catch (IllegalAccessException e) {
		 		e.printStackTrace();
			}
			
			 
		 
		}
		if(result==0)
			return true;
		else
			return false;
	}
	
	
	
 	 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 
			
	}


	public String getFinalinvokemethod() {
		return finalinvokemethod;
	}


	public void setFinalinvokemethod(String finalinvokemethod) {
		this.finalinvokemethod = finalinvokemethod;
	}
	 
	@Override
	protected void finalize() throws Throwable {
		 System.out.println("统计对像被回收.......................");
		super.finalize();
	}

	public LinkedHashMap<String, FieldInf> getAllfieldinf() {
		return allfieldinf;
	}

	public void setAllfieldinf(LinkedHashMap<String, FieldInf> allfieldinf) {
		this.allfieldinf = allfieldinf;
		 
	}

	public String getSecondGroupy() {
		return secondGroupy;
	}

	public void setSecondGroupy(String secondGroupy) {
		this.secondGroupy = secondGroupy;
	}
	private String RenderResizejavaScript()
	{
		StringBuffer sb=new StringBuffer("<script language=\"javascript\">");
		sb.append("function MouseDownToResize(obj){setTableLayoutToFixed();  ")
		.append(" obj.mouseDownX=event.clientX; ").append(" obj.pareneTdW=obj.parentElement.offsetWidth; obj.pareneTableW=").append(this.modulename).append(".offsetWidth;")
		.append(" obj.setCapture(); } ").append(" function MouseMoveToResize(obj){   if(!obj.mouseDownX) return false; ")
		.append("   var newWidth=obj.pareneTdW*1+event.clientX*1-obj.mouseDownX; ").append("   if(newWidth>0)   { ")
		.append(" obj.parentElement.style.width = newWidth; ").append(this.modulename).append(".style.width=obj.pareneTableW*1+event.clientX*1-obj.mouseDownX; }}")
		.append(" function MouseUpToResize(obj){ obj.releaseCapture(); obj.mouseDownX=0; } ").append(" function setTableLayoutToFixed(){ ")
		.append("if(").append(this.modulename).append(".style.tableLayout=='fixed') return; var headerTr=").append(this.modulename).append(".rows[0]; ")
		.append(" for(var i=0;i<headerTr.cells.length;i++) { headerTr.cells[i].styleOffsetWidth=headerTr.cells[i].offsetWidth; }")
		.append("  for(var i=0;i<headerTr.cells.length;i++) { headerTr.cells[i].style.width=headerTr.cells[i].styleOffsetWidth; }").append(this.modulename)
		.append(".style.tableLayout='fixed'; }");
	  	sb.append("</script>");
		return sb.toString();
	}

	public String getModulename() {
		return modulename;
	}

	public void setModulename(String modulename) {
		this.modulename = modulename;
	}

	public String getDetailtablelayout() {
		return detailtablelayout;
	}

	public void setDetailtablelayout(String detailtablelayout) {
		this.detailtablelayout = detailtablelayout;
	}

	public String getDetailsortfildrecord() {
		return detailsortfildrecord;
	}

	public void setDetailsortfildrecord(String detailsortfildrecord) {
		this.detailsortfildrecord = detailsortfildrecord;
	}

	public String getRankfield() {
		return rankfield;
	}

	public void setRankfield(String rankfield) {
		this.rankfield = rankfield;
	}

	public ArrayList<DataSource> getSource() {
		return source;
	}

	public void setSource(ArrayList<DataSource> source) {
		this.source = source;
	}

}
